<script setup>
import { ref, watch } from 'vue'

const question = ref('?')
const answer = ref('Questions usually contain a question mark. ;-)')
const imgsrc = ref('')

// 可以直接侦听一个 ref
watch(question, async (newQuestion, oldQuestion) => {
  if (newQuestion.indexOf('?') > -1) {
    answer.value = '让我想一想...'
    try {
      //fetch get 取数据{"answer":"yes","forced":false,"image":"https://yesno.wtf/assets/yes/4-c53643ecec77153eefb461e053fb4947.gif"}
      const res = await fetch('https://yesno.wtf/api')
      const ans = await res.json()
      console.log(ans)
      answer.value = ans.answer
      imgsrc.value = ans.image
    } catch (error) {
      answer.value = 'Error! Could not reach the API. ' + error
    }
  }
  // 立即执行，且当 `source` 改变时再次执行
},{immediate:true})
</script>

<template>
  <p>
    Ask a yes/no question:
    <input v-model="question" />
  </p>
  <p>{{ answer }}</p>
  <img :src="imgsrc" alt="">
</template>
<style>
img{
  width: 180px;
  height: 90px;
}

</style>

